<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
     <!--查询表单  :inline横向表单-->
      <el-form :inline="true">
        <el-form-item label="用户名：">
          <el-input
            v-model="queryInfo.userName"
            placeholder="请输入用户名"
            label-width="50px"
          ></el-input>
        </el-form-item>
        <!-- label组件前文本 -->
        <el-form-item label="角色：">
          <!-- <el-input v-model="searchObj.name" placeholder="讲师"/> -->
          <!-- trigger-on-focus点击不触发
        fetch-suggestions 是一个返回输入建议的方法属性
        value-key输入建议对象中用于显示的键名默认是value，要改为name，不然显示不出来 -->
          <el-select
            v-model="queryInfo.userType"
            clearable
            placeholder="状态"
          >
            <el-option label="会员" value="1"></el-option>
            <el-option label="商家" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态：">
          <!-- clearable删除已选的值 -->
          <el-select
            v-model="queryInfo.freeze"
            clearable
            placeholder="状态"
          >
            <el-option value="0" label="正常" />
            <el-option value="1" label="禁用" />
            <el-option value="2" label="待审核" />
            <el-option value="3" label="审核通过" />
            <el-option value="4" label="审核不通过" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryInfo.joinDateBegin"
            placeholder="开始时间"
            value-format="yyyy-MM-dd"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="getUserList()"
            >查询</el-button
          >
          <el-button type="default" @click="resetData()">清空</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表区域 -->
      <!-- border边框线  stripe创建带斑马纹的表格  type="index"索引列-->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" />
        <el-table-column label="用户名" prop="userName" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="学校" prop="school" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="电话" prop="phone" />
        <el-table-column label="角色" prop="userType">
        
           <template slot-scope="scope">
          <el-tag v-if="scope.row.userType==1" type="success">会员</el-tag>
          <el-tag v-if="scope.row.userType==2" type="warning">商家</el-tag>
           </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <!-- 作用域插槽 slot-scope="scope" {{scope.row}}获取这一行的数据 -->
           <template slot-scope="scope" >
             <p v-if="scope.row.freeze==0">正常</p>
             <p v-if="scope.row.freeze==1">冻结</p>
             <p v-if="scope.row.freeze==2">待审核</p>
             <p v-if="scope.row.freeze==3">审核通过</p>
             <p v-if="scope.row.freeze==4">审核不通过</p>
          
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210px">
          <!-- 作用域插槽 slot-scope="scope" {{scope.row}}获取这一行的数据 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <!-- scope.row.id获取这行的用户id -->
            <el-button
              type="primary"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >
            编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              @click="removeUserById(scope.row.id)"
            >
            删除
            </el-button>
            <!-- 冻结按钮 -->
            <!-- enterable 鼠标是否可进入到 tooltip 中 -->
              <el-button
              v-if="scope.row.freeze==0 ||scope.row.freeze==3"
                type="warning"
                size="mini"
                @click="editFreeze(scope.row.id,1)"
              >禁用</el-button>
              <el-button
              v-if="scope.row.freeze==1"
                type="warning"
                size="mini"
                @click="editFreeze(scope.row.id,0)"
              >解除</el-button>
              	<router-link :to="'/storeVerify/'">
               <el-button
              v-if="scope.row.freeze==2"
                type="warning"
                size="mini"
              >审核</el-button>
                </router-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <!--  changeCurrentPage()不能加括号，应该下面函数有参数，这里不给值默认会传undefined -->
      <!-- 
         @size-change 监听 pagesize改变的事件 （选择显示多少条数据）
         @current-change  currentPage当前页数 改变时会触发 下一页
          current-page当前页数
          page-sizes 每页显示个数选择器的选项设置
          total总条目数 page-size每页显示条目个数默认10 prev上一页 pager页数 next下一页
          sizes选择器
         -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

  

    <!-- 修改用户的对话框 -->
    <!-- :visible.sync= addDialogVisbile 为false 隐藏对话框 
    @close事件 当关闭表单重置表单数据 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <!-- ref重置表单时需要获取全局对象；  rules 表单验证;  model 绑定input属性值 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="70px"
        :rules="editFormRules"
      >
        <!-- prop表单验证规则具体属性 disabled禁止修改-->
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName" disabled></el-input>
        </el-form-item>
         <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" ></el-input>
        </el-form-item>
       
         <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="editForm.sex">
           <el-radio v-model="editForm.sex"  label="0">男</el-radio>
           <el-radio v-model="editForm.sex" label="1">女</el-radio>
            </el-radio-group>
        </el-form-item>
         <el-form-item label="生日" prop="birthday">
          <el-date-picker type="date" placeholder="选择日期" v-model="editForm.birthday" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
          <el-form-item label="学校" prop="school">
          <el-input v-model="editForm.school" ></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>




   
  </div>
</template>

<script>
export default {
  data() {
    //自定义验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      //验证通过
      if (regEmail.test(value)) {
        //合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    //自定义验证手机号的规则
    var checkMoblie = (rule, value, cb) => {
      //验证手机号的正则表达式
      // const regMoblie = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      const regMoblie = /^1[1356789]\d{9}$/
      //验证通过
      if (regMoblie.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: '',
        //当前的页数
        current: 1,
        //当前每页显示多少条数据
        size: 5,
      },
      userlist: [],
      total: 0,
      //控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      //查询到的用户对象
      editForm: {
        sex:'0'
      },
      editFormRules: {
        email: [
          //validator指定自定义的校验规则
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          //validator指定自定义的校验规则
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMoblie, trigger: 'blur' },
        ],
      },
      
     
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get(
        'api/service-auth/admin/user/list',
        {
          params: this.queryInfo,
        }
      )
      if (res.code != 200) {
        return this.$message.error('获取用户列表失败!')
      }
      this.userlist = res.data.records
      // console.log(this.userlist)
      this.total = res.data.total
    },

    // 监听 pagesize改变的事件（选择显示多少条数据）
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.size = newSize
      this.getUserList()
    },
    //监听 页码值下一页 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.current = newPage
      this.getUserList()
    },
  
    //展示编辑用户的对话框
    async showEditDialog(id) {
      // console.log(id)t
      const { data: res } = await this.$http.get('api/service-auth/admin/user/list' ,{
              params: {id:id},
      })
      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      //赋值给编辑用户对象
      this.editForm = res.data.records[0]
      //点击编辑按钮打开对话框
      this.editDialogVisible = true
    },

    //监听修改用户对话框的关闭事件
    editDialogClosed() {
      // loginFormRef是el-form ref属性值   resetFields()对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.editFormRef.resetFields()
    },

    //修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return
        //发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'api/service-auth/admin/user/edit',this.editForm
        )

        if (res.code !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据列表
        this.getUserList()
        //提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },

      // 重置表单
    resetData() {
      this.queryInfo = {
        //当前的页数
        current: 1,
        //当前每页显示多少条数据
        size: 5,
      }
      this.getUserList()
    },

    //根据用户id删除用户
    async removeUserById(id) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      //如果用户确认删除，则返回值为字符串confirm
      //如果用户取消了删除，则返回值为字符串 cancel
      //  console.log(res)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('api/service-auth/admin/user/delete/' + id)

      if (res.code !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功！')
      //刷新列表
      this.getUserList()
    },


 

     //更新状态
    async editFreeze(id,status){
       //弹框询问商品是否删除数据
      if (status == 1) {
        const confirmResult = await this.$confirm(
          '此操作将禁用该账户, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).catch((err) => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消禁用')
        }
      } else {
        const confirmResult = await this.$confirm(
          '此操作将恢复该账号, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success',
          }
        ).catch((err) => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消恢复')
        }
      }
       const { data: res } = await this.$http.put(
        `api/service-auth/admin/user/editFreeze/`+id,
        {
          freeze: status,
        }
      )
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success("修改成功！")
      //刷新列表
      this.getUserList()
    },
  

   

  },
}
</script>

<style lang="less" scoped>
</style>